package com.nti56.springboot.controller;



import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.util.StringUtil;
import com.nti56.springboot.cache.BaseDataCache;
import com.nti56.springboot.model.DictItem;
import com.nti56.springboot.model.MachProduct;
import com.nti56.springboot.model.MachRunTime;
import com.nti56.springboot.model.PageResponse;
import com.nti56.springboot.service.MachProductService;
import com.nti56.springboot.service.MachRunTimeService;
import com.nti56.springboot.utils.Constant;
import com.nti56.springboot.utils.DateUtil;
import com.nti56.springboot.utils.DictConstant;
import com.nti56.springboot.utils.ParamUtil;
import com.nti56.springboot.utils.ParamUtil.Param;



@RequestMapping("machRunTime")
@Controller
public class MachRunTimeController extends BaseController{
    
	private static final Logger logger = LoggerFactory.getLogger(MachRunTimeController.class);

	
	@Autowired
    private MachRunTimeService machRunTimeService;
	@Autowired
    private BaseDataCache baseDataCache;
	@Autowired
	private MachProductService machProductService;
	
	@RequestMapping("/toMachRunTimeList")
    public String toMachRunTimeList(Map<String,Object> map,Model model){
		List<DictItem> dictMachTypeItems = baseDataCache.getDictItemsByDictCode(DictConstant.DICT_MACH_TYPE);
		model.addAttribute("dictMachTypeItems", dictMachTypeItems);
		return "cnc/machRunTimeStateList";
    }
	
	
	/**
	 * 使用 easyexcel导出  每日 4中状态时长报表
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@GetMapping("download")
    public void download(HttpServletRequest request,HttpServletResponse response) throws IOException {
		Map map = this.getParamMap(request);
		List<MachRunTime> list = this.machRunTimeService.findAll(map);
        if(list!=null) {
			/*
			 * response.setContentType("application/vnd.ms-excel");
			 * response.setCharacterEncoding("utf-8"); // 这里URLEncoder.encode可以防止中文乱码
			 * 当然和easyexcel没有关系 String fileName = URLEncoder.encode("机台运行状态报表", "UTF-8");
			 * response.setHeader("Content-disposition", "attachment;filename=" +
			 * URLEncoder.encode( fileName + ".xlsx", "utf-8" ));
			 * EasyExcel.write(response.getOutputStream(),
			 * MachRunTime.class).sheet("sheet1").doWrite(list);
			 */
        	
        	
        	HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("sheet1");
            String fileName = URLEncoder.encode("机台运行状态报表.xlsx", "UTF-8");//设置要导出的文件的名字
            //新增数据行，并且设置单元格数据
            int rowNum = 1;
            String[] headers = { "生产日期", "班次", "机台编号", "运行时长(秒)", "停止时长(秒)", "报错时长(秒)", "离线时长(秒)"};
            //headers表示excel表中第一行的表头
            HSSFRow row = sheet.createRow(0);
            //在excel表中添加表头
            for(int i=0;i<headers.length;i++){
                HSSFCell cell = row.createCell(i);
                HSSFRichTextString text = new HSSFRichTextString(headers[i]);
                cell.setCellValue(text);
            }
            //在表中存放查询到的数据放入对应的列
            for (int i=0;i<list.size();i++) {
                HSSFRow row1 = sheet.createRow(rowNum);
                sheet.autoSizeColumn(i);
                row1.createCell(0).setCellValue(DateUtil.format(list.get(i).getProDate(), DateUtil.DATE_PATTERN));
                row1.createCell(1).setCellValue(list.get(i).getShift());
                row1.createCell(2).setCellValue(list.get(i).getMachNum());
                row1.createCell(3).setCellValue(list.get(i).getRunTime());
                row1.createCell(4).setCellValue(list.get(i).getStandBy());
                row1.createCell(5).setCellValue(list.get(i).getAlarm());
                row1.createCell(6).setCellValue(list.get(i).getOffLine());
                rowNum++;
            }
           
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            try {
                response.flushBuffer();
                workbook.write(response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
	
	/**
	 * 超出产量报表
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@GetMapping("downloadChanliang")
    public void downloadChanliang(HttpServletRequest request,HttpServletResponse response) throws IOException {
		
		String shift = (String) request.getParameter("shift");
		String machNum = (String) request.getParameter("machNum");
		String proDateFrom = (String) request.getParameter("proDateFrom");
		String proDateTo = (String) request.getParameter("proDateTo");
		List<MachProduct> list = new ArrayList<MachProduct>();
		Param param = null;
		if(!StringUtil.isEmpty(shift)) {
			//导出一天生产数据    从  视图   2020-01_view
			String tableName = "`"+proDateFrom.substring(0,7)+"_view`";;
			if(Constant.CNC_X_AM.equals(shift)) {
				param = ParamUtil.setParam("fromTime", proDateFrom+" "+Constant.CNC_SHIFT_AM)
								 .setParam("toTime", proDateTo+" "+Constant.CNC_SHIFT_PM)
								 .setParam("tableName", tableName)
								 .setParam("machNum", machNum);
			}else {
				param.setParam("fromTime", proDateFrom+" "+Constant.CNC_SHIFT_PM)
					 .setParam("tableName", tableName)
					 .setParam("machNum", machNum);
			}
			
		}else {
			//导出时间跨度数据  从表  2020-01
			String tableName = "`"+proDateFrom.substring(0,7)+"`";
			param = ParamUtil.setParam("machNum", machNum)
					 .setParam("tableName", tableName)
					 .setParam("fromTime", proDateFrom+" "+Constant.CNC_SHIFT_AM)
					 .setParam("fromTime", proDateTo+" "+Constant.CNC_SHIFT_PM);
		}
		list = machProductService.findAll(param);
		this.exportChanLiang(machNum,list, request, response);
	}
	
	
	private void exportChanLiang(String machNum,List<MachProduct> list,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
		HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("sheet1");
        String fileName = URLEncoder.encode("机台_"+machNum+"_产量报表.xlsx", "UTF-8");//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        String[] headers = { "生产日期", "机台编号", "产量"};
        //headers表示excel表中第一行的表头
        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        //在表中存放查询到的数据放入对应的列
        for (int i=0;i<list.size();i++) {
            HSSFRow row1 = sheet.createRow(rowNum);
            sheet.autoSizeColumn(i);
            row1.createCell(0).setCellValue(DateUtil.format(list.get(i).getTime(), DateUtil.DATE_PATTERN));
            row1.createCell(1).setCellValue(list.get(i).getMachNum());
            row1.createCell(2).setCellValue(list.get(i).getProCount());
            rowNum++;
        }
       
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        try {
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	
	@RequestMapping("/listMachRunTimes")
    @ResponseBody
    public PageResponse listMachRunTimes(HttpServletRequest request){
    	Map map = this.getParamMap(request);
    	this.startPage(request);
        List<MachRunTime> list = this.machRunTimeService.findAll(map);
        return this.getPageResponse(list);
    }
	
	
	
	
	
}